const express = require('express');

const multer = require('multer');
const mkdirp = require('mkdirp');
const path = require('path');
const { log } = require('console');

const router = express.Router();
// 获取当前的日期
const nowDate = Date.parse(new Date());

// 封装保存上传文件功能
const upload = () => {
  const storage = multer.diskStorage({
    destination: async (req, file, cb) => {
      // 指定上传后保存到哪一个文件夹中
      await mkdirp(`./static/uploads/${nowDate}`); // 创建目录
      cb(null, `static/uploads/${nowDate}`); //
    },
    filename: (req, file, cb) => {
      // 给保存的文件命名
      let extname = path.extname(file.originalname); // 获取后缀名

      let fileName = path.parse(file.originalname).name; // 获取上传的文件名
      cb(null, `${fileName}-${Date.now()}${extname}`);
    },
  });

  return multer({ storage });
};
/*
	pic 	为前端调用上传接口的参数名,可以定义其他的,需要和前端约定好

*/

router.post('/upImg', upload().single('file'), (req, res) => {
  res.send({
    // 给前端返回的数据
    body: req.body,
    file: req.file,
    path: `static/uploads/${nowDate}/${req.file.filename}`,
    fullPath:`http://localhost:3000/static/uploads/${nowDate}/${req.file.filename}`
  });
});

module.exports = router;
